package com.zhongge.servlet;

import com.zhongge.entity.Student;
import com.zhongge.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *@ClassName UpdateSaveServlet
 *@Description  TODO
 *@Author zhongge
 *@Version 1.0
 */
@WebServlet("/updateSave")
public class UpdateSaveServlet extends HttpServlet {
    StudentService studentService = new StudentService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //为了数据格式一致，设置一下字符集
        req.setCharacterEncoding("UTF-8");
        //得到前端提交的数据==》有参数获取值==》以键值对的方式提交
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String address = req.getParameter("address");
        String remark = req.getParameter("remark");

        //获取id 根据id得出当前操作的学生对象
        String id = req.getParameter("id");
        Student student = studentService.getById(Integer.parseInt(id));

        //对该学生修改==》掉用set方法
        student.setName(name);
        student.setAge(Integer.parseInt(age));
        student.setSex(Integer.parseInt(sex));
//日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
        Date date;
        try {
            date = simpleDateFormat.parse(birthday);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        student.setBirthday(date);

        student.setAddress(address);

        student.setRemark(remark);

        //属性设置后==》得存到数据库
        studentService.updateById(student);

        //修改后==》直接重新查询刷新 更新 list 即可==》所以转发到 list servlet
        req.getRequestDispatcher("list").forward(req, resp);
    }
}
